<template>
    <van-nav-bar left-arrow @click-left="onClickLeft" />
    <!-- :style="`transform: translateY(-${Y}px);`" -->
    <div class="detail" v-if="article.data" ref="$box">
        <h3>{{ article.data.article_title }}</h3>
        <p>作者: {{ article.data.article_author }}</p>
        <p>时间: {{ moment(article.data.article_create_time).format("YY-MM-DD hh:mm:ss") }}</p>
        <hr>
        <div v-if="article_type == 1">
            <p>
                {{ article.data.article_content }}
            </p>
        </div>

        <div v-else-if="article_type == 2">
            <div class="article" v-html="article.data.article_content"></div>
        </div>

        <div v-else>
            图片
        </div>
    </div>

    <div class="goTop">
        <!-- 评论 -->
        <span @click="showPopup" class="comment"></span>
        <!-- 收藏 -->
        <span @click="addLike" :class="['like', isLike == true ? 'like-on' : '']"></span>
        <!-- 顶部 -->
        <span @click="goTopFn" class="top" v-if="isShow"></span>
    </div>


    <!-- 评论 -->
    <!-- 底部弹出 -->
    <van-popup round v-model:show="showBottom" position="bottom" :style="{ height: '50%' }">
        <!-- 内容 -->
        <div class="comment-box">
            <!-- 评论列表 -->
            <div class="list-box">
                <ul v-if="comment.list.length != 0">
                    <li>当前文章评论</li>
                    <br>
                    <li v-for="item in comment.list" :key="item.id">
                       <div class="left">
                          <!-- <span>用户</span> -->
                          <div class="img-box">
                              <img v-if="item.user_url" :src="item.user_url" alt="">
                          </div>
                       </div>
                       <div class="right">
                            <p>{{ item.comment_content }}</p>
                            <p>{{ moment(item.comment_create_time).format("YY-MM-DD hh:mm:ss") }}</p>
                       </div>
                    </li>
                </ul>

                <div v-else>
                    <van-empty description="当前文章还没有评论。" />
                </div>

            </div>
            <!-- 输入评论 -->
            <div class="input-box">
                <van-cell-group inset>
                    <van-field v-model="inpMessage" center clearable placeholder="发送评论">
                        <template #button>
                            <!-- 点击发送评论 -->
                            <van-button @click="addComment" size="small" type="primary">发送</van-button>
                        </template>
                    </van-field>
                </van-cell-group>
            </div>
        </div>
    </van-popup>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getArticleDetail } from '../api/index'
import { addLikeFuc, removeLikeFuc, detailLikeFuc, addCommentFunc,getCommentList, getUserImage } from '../api/index'
import moment from 'moment'
import { showToast } from 'vant'


const $router = useRouter()
const $route = useRoute()
const $box = ref(null)
// 初始化 收藏
let isLike = ref(false)
// 纯文字：article_type: 1 ;  图片和文本：article_type: 2 ;  图片：article_type: 3
let article_type: any = ref(1)
let article_id: any = ref('')
article_type.value = $route.query?.article_type
article_id.value = $route.query?.article_id
let article: any = reactive({ data: {} })
let isShow = ref(false)
let inpMessage = ref('')
let scrollTop = 0
let Y = ref(0)
let index = 0
// let points: any = [];// 图个方便
let points: Array<{ article_id: string, scrollTop: number }> = []
let str = localStorage.getItem('POINTS')
let comment: any = reactive({list: []})

// 控制弹出层组件
const showBottom = ref(false)

const showPopup = () => {
    showBottom.value = true;
}

const onClickLeft = () => {
    // console.log('返回')
    $router.back();
}

// 获取评论的方法
const getCommentFn = async (article_id: string)=> {
    await getCommentList({article_id})
    .then(
        content=>{
            // console.log('7.0',content)
            if(content.code == 200){
                // 赋值
                // comment.list = content.result;
                return content.result;
            }
        }
    )
    .then(
        // 整合数据（获取评论的用户头像）
        async (result) =>{
            // 循环评论
            for(let i = 0 ; i < result.length ; i ++) {
                await getUserImage({user_id: result[i].from_user_id})
                .then(
                    data=>{
                        // console.log('8.0',data)
                        if(data.code == 200) {
                            result[i].user_url = data.user_url;
                        }
                    }
                )
            }

            let arr = result.sort((prev: any ,next: any)=> {
                return  next.id - prev.id;
            })
            // 赋值
            comment.list = arr;
        }
    )
}

// 编写初始化函数
const initFn = async () => {
    // 获取文章
    await getArticleDetail({ article_id: article_id.value })
        .then(
            content => {
                if (content.code == 200) {
                    // console.log(content.result[0])
                    article.data = content.result[0];
                    // 调用函数获取文章评论列表
                    getCommentFn(content.result[0].article_id)
                }
            }
        )
    // 查看文章是否收藏
    await detailLikeFuc({ article_id: article_id.value })
        .then(
            content => {
                // console.log('xx',content)
                if (content.code == 200 || content.code == 1) {
                    isLike.value = true;
                }
                else {
                    isLike.value = false;
                }
            },
            err=> {
                console.log('yy',err);
            }
        )

}


// 返回顶部
const goTopFn = () => {
    // BOM
    window.scrollTo(0, 0)
}

// 监听页面滚动
window.addEventListener('scroll', () => {
    // console.log('test')
    // 获取页面被浏览器卷掉部分
    scrollTop = document.documentElement.scrollTop;
    Y.value = scrollTop;
    // console.log({ scrollTop })
    if (scrollTop > 100) {
        isShow.value = true;
        // 缓存数据
        let isHas = points.some((item, i) => {
            if (item.article_id == article_id.value) {
                index = i;
                return true;
            }
        })
        if (!isHas) {
            // 添加数据
            points.push({ article_id: article_id.value, scrollTop })
        }
        else {
            // 修改数据
            points[index].scrollTop = scrollTop;
        }
        // 缓存数据
        localStorage.setItem('POINTS', JSON.stringify(points))
    }
    else {
        isShow.value = false;
    }
})

// 点击收藏
const addLike = async () => {
    // console.log("是否收藏:",isLike.value)
    if (isLike.value) {
        await removeLikeFuc({ article_id: article_id.value })
            .then(
                content => {
                    // console.log('3.0', content)
                    if (content.code == 200) {
                        // 取消收藏
                        isLike.value = false;
                    }
                    else {
                        showToast(content.msg)
                    }
                },
                err=>{
                    console.log('4.0',err);
                }
            )

    }
    else {
        // 收藏
        // article_id, article_title 
        await addLikeFuc({
            article_id: article_id.value,
            article_title: article.data.article_title,
            token: localStorage.getItem('auto_token')
        })
            .then(
                content => {
                    // console.log('1.0',content)
                    if (content.code == 200 || content.code == 1) {
                        // 收藏成功
                        isLike.value = true;
                    }
                    else {
                        showToast(content.msg)
                    }
                }
            )
    }
}

// 点击发布评论
const addComment = async ()=> {

    if(inpMessage.value == ""){
        return;
    }
    // 输入框有值
    await addCommentFunc({
        to_user_id: article.data.user_id,
        comment_content : inpMessage.value,
        article_id: article.data.article_id,
        token: localStorage.getItem('auto_token')
    })
    .then(
        content=> {
            // console.log('6.0',content);
            if(content.code == 200) {
                // 重新获取评论列表
                getCommentFn(article.data.article_id);
            }

            // 重置输入框
            inpMessage.value = "";
        }
    )
}


// 初始化
initFn();

// 当阅读这篇文章了，下次在查阅这篇文章时，设置文章为上次阅读历史位置
if (str) {
    points = JSON.parse(str);
    points.forEach((item) => {
        if (item.article_id == article_id.value) {
            // scrollTop = item.scrollTop;
            Y.value = item.scrollTop;
        }
    })
}


// 测试返回顶部示例：
// window.scrollTo(x,y);
// window.scrollTo(0,-700);
// onMounted(()=> {
//     // console.log($box.value);
//     let div: any = $box.value;
//     if(div){
//         div.style['transform']=`translateY(${-700}px)`;
//     }
// })

</script>

<style lang="less">
@import '@/static/less/common.less';
::-webkit-scrollbar {
    display: none;
}
.list-box {
    padding: .4rem .5333rem;
    width: 100%;
    box-sizing: border-box;
    overflow: scroll;
    ul {
        overflow: scroll;
        padding-bottom: 2.6667rem;
        li {
            width: 100%;
            border-bottom: 1px solid #ccc;
            padding: 0 .2667rem;
            box-sizing: border-box;
            margin-top: .1633rem;
            line-height: 170%;
            display: flex;
            align-items: flex-start;
            .left {
                padding: 0 .16rem 0 0 ;
                font-weight: bold;
                .img-box {
                    width: 1.3rem;
                    height: 1.3rem;
                    border-radius: 50%;
                    overflow: hidden;
                    text-align: center;
                    overflow: hidden;
                    img {
                        width: 100%;
                        vertical-align: middle;
                    }
                }
            }
            p:last-child{
                font-size: 14px;
                color: #666;
            }
        }
    }
}

.input-box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    box-sizing: border-box;
    .van-cell-group--inset {
        box-sizing: border-box;
        border-radius: 0;
        transform: translateY(-10px);
    }
    .van-cell {
        border: 1px solid deepskyblue;
    }
}

.base() {
    background-position: center;
    background-size: 80%;
    background-repeat: no-repeat;
    background-color: transparent;
    border: 0;
}

// 图标：https://www.iconfont.cn/
.goTop {
    position: fixed;
    right: .48rem;
    bottom: 5.3333rem;
    background-color: rgba(0, 0, 0, .4);
    border-radius: .5333rem;

    a,
    span {
        display: block;
        width: 1.1733rem;
        height: 1.1733rem;
        background-color: rgba(255, 255, 255, .75);
        text-align: center;
        line-height: 1.1733rem;
        border-radius: 50%;
        color: #666;
        margin-top: .2667rem;
        border: 1px solid #ccc;
        font-size: 14px;
    }

    .comment {
        background-image: url(../static/img/i-comment.png);
        .base();
    }

    .top {
        background-image: url(../static/img/i-top.png);
        .base();
        background-size: 60%;
    }

    .like {
        background-image: url(../static/img/i-like.png);
        .base();
    }

    .like-on {
        background-image: url(../static/img/i-like-on.png);
    }
}

.detail {
    padding: @pad;

    >h3 {
        padding-bottom: .2667rem;
    }

    p {
        line-height: 170%;
    }
}

.article {
    line-height: 170%;

    a {
        color: #000;
    }

    img {
        width: 100%;
    }

    h3,
    h2,
    h1,
    h4,
    h5 {
        font-weight: normal;
        padding-bottom: .2667rem;
        padding-top: .2667rem;
        font-size: 16px;
    }

    p {
        color: #666;
    }
}
</style>